<template>
  <div class="users">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="user">
      <div class="search" style="margin-bottom: 10px;">
        <el-input v-model="state4" placeholder="请输入内容" class="search-input"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="uploadsearch"></el-button>
        <el-button type="primary" plain @click="handlAdd">添加用户</el-button>
      </div>
      <div class="userlist">
        <el-table border :data="tableData" style="width: 100%" v-loading="loading">
          <el-table-column type="index" width="50"></el-table-column>
          <!-- <el-table-column prop="id" label="#" width="94"></el-table-column> -->
          <el-table-column prop="username" label="姓名" width="240"></el-table-column>
          <el-table-column prop="email" label="邮箱" width="240"></el-table-column>
          <el-table-column prop="mobile" label="电话" width="240"></el-table-column>
          <el-table-column prop="mg_state" label="操作" width="240">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="handleState(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="more" label="操作" width="240">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                @click="handleEdit(scope.row)"
                icon="el-icon-edit"
              ></el-button>
              <el-button
                size="mini"
                type="primary"
                @click="handleDelete(scope.row)"
                icon="el-icon-delete"
              ></el-button>
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-check"
                @click="handleSelect(scope.row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加用户弹框 -->
      <div class="addusers">
        <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
          <el-form :model="addForm" :rules="fromRules" ref="addRef">
            <el-form-item label="用户名" label-width="90px" prop="username">
              <el-input v-model="addForm.username" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" label-width="90px" prop="password">
              <el-input v-model="addForm.password" type="password" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" label-width="90px" prop="email">
              <el-input v-model="addForm.email" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="电话" label-width="90px" prop="mobile">
              <el-input v-model="addForm.mobile" auto-complete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="uploadUsers">确 定</el-button>
          </div>
        </el-dialog>
      </div>
      <!-- 编辑用户弹框 -->
      <div class="editusers">
        <el-dialog title="编辑用户" :visible.sync="editdialogFormVisible">
          <el-form :model="editrow" :rules="fromRules" ref="editRef">
            <el-form-item label="用户名" label-width="90px">
              <el-input v-model="editrow.username" auto-complete="off" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" label-width="90px" prop="email">
              <el-input v-model="editrow.email" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="电话" label-width="90px" prop="mobile">
              <el-input v-model="editrow.mobile" auto-complete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer">
            <el-button @click="editdialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="uploadEdit">确 定</el-button>
          </div>
        </el-dialog>
      </div>
      <!-- 分配角色弹框 -->
      <div class="selectUser">
        <el-dialog title="分配角色" :visible.sync="selectdialogFormVisible">
          <el-form :model="checkForm">
            <el-form-item>
              <span id="selectTag">用户名 ：</span>
              <el-tag type="danger">{{checkForm.username}}</el-tag>
            </el-form-item>
            <el-form-item>
              <span>选择角色：</span>
              <el-select v-model="selectRoleId" placeholder="请选择">
                <el-option
                  v-for="item in selectData"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer">
            <el-button @click="selectdialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="uploadSelect">确 定</el-button>
          </div>
        </el-dialog>
      </div>
      <!-- 分页按钮 -->
      <div class="pagenum">
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagenum"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="5"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { homeData, addUser, delUser, editUser, changeUserState, selectList, uploadSelect } from '@/api'
export default {
  created () {
    this.initList('')
  },
  data () {
    // 创建自定义的校验函数
    let checkEmail = (rule, value, cb) => {
      if (value === '') {
        cb(new Error('请输入邮箱'))
      } else {
        // 接着需要格式是否正确
        let emailReg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
        if (emailReg.test(value)) {
          // 校验通过
          cb()
        } else {
          // 校验不通过
          cb(new Error('请输入正确的邮箱格式'))
        }
      }
    }
    return {
      state4: '',
      tableData: [],
      pagesize: 5,
      total: 0,
      loading: true,
      dialogFormVisible: false,
      editdialogFormVisible: false,
      selectdialogFormVisible: false,
      currentPage: 0,
      pagenum: 1,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editrow: {
        username: '',
        email: '',
        mobile: '',
        id: ''
      },
      checkForm: {
        username: '',
        id: ''
      },
      // 分配角色下拉菜单
      selectData: [],
      selectRoleId: '',
      // 添加用户的表单验证
      // /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
      fromRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        // email: [
        //   { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        //   { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        // ],
        email: [
          { required: true, validator: checkEmail, trigger: ['blur', 'change'] }
        ],
        mobile: [
          { required: true, message: '电话不能为空', trigger: 'blur' }
        ]
      }
    }
  },

  methods: {
    // 初始化列表
    initList (uploadTxt, pagenum = 1) {
      this.loading = true
      homeData({ query: uploadTxt, pagenum: this.pagenum, pagesize: this.pagesize })
        .then(res => {
          console.log(res)

          this.tableData = res.data.data.users
          this.total = res.data.data.total
          this.$message.success('获取管理员列表成功')
          this.loading = false
        })
    },
    // 添加
    uploadUsers () {
      this.$refs.addRef.validate(isPass => {
        if (isPass) {
          addUser(this.addForm)
            .then(res => {
              console.log(res)
              if (res.data.meta.status === 201) {
                this.$message(res.data.meta.msg)
                this.initList('')
                this.dialogFormVisible = false
                this.addForm.username = ''
                this.addForm.password = ''
                this.addForm.email = ''
                this.addForm.mobile = ''
              } else {
                this.$message.error(res.data.meta.msg)
              }
            })
        } else {
          this.$message.error('请输入正确的信息')
        }
      })
    },
    // 搜索功能
    uploadsearch () {
      let searchText = this.state4.trim()
      this.pagenum = '1'
      this.initList(searchText)
    },
    // 点击添加按钮
    handlAdd () {
      this.dialogFormVisible = true
      this.$nextTick(() => {
        // 清除校验信息需要调用form表单的clearValidate()方法
        this.addForm.username = ''
        this.addForm.password = ''
        this.addForm.email = ''
        this.addForm.mobile = ''
        this.$refs.addRef.clearValidate()
      })
    },
    // 改变状态操作
    handleState (row) {
      console.log(row)
      changeUserState(row.id, row.mg_state)
        .then(res => {
          console.log(res)
          if (res.data.meta.status === 200) {
            this.$message.success(res.data.meta.msg)
          } else {
            this.$message.error(res.data.meta.msg)
          }
        })
    },
    // 编辑操作
    handleEdit (row) {
      console.log(row)
      this.editdialogFormVisible = true
      this.editrow.id = row.id
      this.editrow.username = row.username
      this.editrow.email = row.email
      this.editrow.mobile = row.mobile
      console.log(this.editrow)
    },
    // 确认编辑
    uploadEdit () {
      editUser(this.editrow)
        .then(res => {
          if (res.data.meta.status === 200) {
            this.$message.success(res.data.meta.msg)
            this.initList()
            this.editdialogFormVisible = false
          } else {
            this.$message.error(res.data.meta.msg)
          }
        })
    },
    // 删除操作
    handleDelete (row) {
      console.log(row)
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.tableData.length === 1 && this.total !== 1) {
          this.pagenum -= 1
        }
        // 点击确定执行的操作
        delUser(row.id)
          .then(res => {
            if (res.data.meta.status === 200) {
              this.$message.success(res.data.meta.msg)
              this.initList()
            } else {
              this.$message.error(res.data.meta.msg)
            }
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 分配角色列表
    handleSelect (row) {
      console.log(row)
      this.checkForm.username = row.username
      this.checkForm.id = row.id
      this.selectRoleId = row.role_name
      selectList()
        .then(res => {
          console.log(res)
          this.selectData = res.data.data
        })
      this.selectdialogFormVisible = true
    },
    // 提交列表
    uploadSelect () {
      if (typeof this.selectRoleId === 'string') {
        this.selectdialogFormVisible = false
        this.initList()
      }
      uploadSelect(this.checkForm.id, this.selectRoleId)
        .then(res => {
          if (res.data.meta.status === 200) {
            this.$message.success(res.data.meta.msg)
            this.selectdialogFormVisible = false
            this.initList()
          }
        })
      console.log('分配角色')
    },
    // 每页条数
    handleSizeChange (val) {
      this.pagesize = val
      this.initList('')
    },
    // 当前页码
    handleCurrentChange (val) {
      this.pagenum = val
      let searchText = this.state4.trim()
      this.initList(searchText, val)
      this.currentPage = val
    }

  }
}
</script>
<style lang="scss" scoped>
.el-breadcrumb {
  background-color: #f5f5f5;
  height: 45px;
  font-size: 15px;
  padding-left: 10px;
  line-height: 45px;
  margin-bottom: 15px;
}
.user {
  .search-input {
    width: 300px;
  }
  .pagenum {
    margin-top: 10px;
    background-color: #f5f5f5;
  }
  #selectTag {
    margin-right: 8px;
  }
}
</style>
